package com.dzm.service.impl;

import com.dzm.constants.ClientConstant;
import com.dzm.constants.RedisConstant;
import com.dzm.constants.UserConstant;
import com.dzm.except.LoginException;
import com.dzm.to.LoginUser;
import com.dzm.service.ITokenService;
import com.dzm.utils.JwtUtil;
import com.dzm.utils.ResponseEnum;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 作者：Dzm
 * 时间：2024-08-23-19:58
 * 功能：
 */

@Service
public class ITokenServiceImpl implements ITokenService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Map<String, Object> createToken(LoginUser loginUser) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        Map<String, Object> map = new HashMap<>();
        map.put("userId", loginUser.getUser().getUsercode());
        map.put("username", loginUser.getUser().getUsername());
        map.put("user_key", uuid);

        //根据用户信息获取token
        String token = JwtUtil.createToken(map);

        //将token存入idea
        String key = RedisConstant.LOGIN_TOKEN + uuid;
        redisTemplate.opsForValue().set(key, loginUser, 1, TimeUnit.DAYS);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        return resultMap;
    }

    @Override
    public void logout(HttpServletRequest request) {
        String cliToken = request.getHeader(ClientConstant.CLIENT_TOKEN_NAME);
        String token = cliToken.replaceFirst(ClientConstant.CLIENT_TOKEN_PRE, "");

        Claims claims = JwtUtil.parseToken(token);
        String uuid = (String) claims.get(UserConstant.UUID_NAME);

        redisTemplate.delete(RedisConstant.LOGIN_TOKEN + uuid);

    }
}
